#include "../Logs/nhylog.hpp"
#include <iostream>

// 扩展按照时间的落地方向
enum class GAP
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink : public nhylog::LogSink
{
public:
    RollByTimeSink(const std::string basename, GAP gap_type)
        : basename_(basename), cur_gap_(0)
    {
        switch (gap_type)
        {
        case GAP::GAP_SECOND:
            gap_size_ = 1;
            break;
        case GAP::GAP_MINUTE:
            gap_size_ = 60;
            break;
        case GAP::GAP_HOUR:
            gap_size_ = 3600;
            break;
        case GAP::GAP_DAY:
            gap_size_ = 3600 * 24;
            break;
        }

        cur_gap_ = nhylog::util::Date::now() / gap_size_;
        //
        std::string filename = basename + createNewFile();
        //
        nhylog::util::File::createDirectory(nhylog::util::File::path(filename));
        //
        ofs_.open(filename, std::ios::binary | std::ios::app);
    }

    void log(const char *data, size_t len)
    {
        time_t cur = nhylog::util::Date::now();

        if ((cur / gap_size_) != cur_gap_)
        {
            ofs_.close();
            std::string filename = basename_ + createNewFile();
            ofs_.open(filename, std::ios::binary | std::ios::app);
            assert(ofs_.is_open());
        }
        ofs_.write(data, len);
        assert(ofs_.good());
    }

private:
    std::string createNewFile()
    {
        time_t t = nhylog::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream pathname;
        pathname << lt.tm_year + 1900 + '-';
        pathname << lt.tm_mon + 1 + '-';
        pathname << lt.tm_mday + '-';
        pathname << lt.tm_hour + '-';
        pathname << lt.tm_min + '-';
        pathname << lt.tm_sec;
        pathname << ".log";

        return pathname.str();
    }

private:
    // 滚动的标准时间
    int gap_size_;
    // 当前是第几个gap
    int cur_gap_;
    std::string basename_;

    std::ofstream ofs_;
};

int main()
{
    std::unique_ptr<nhylog::LoggerBuider> builder(new nhylog::GlobleLoggerBuider());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerType(nhylog::LoggerType::LOGGER_ASYNC);
    builder->buildEnableUnSafeAsync();
    builder->buildLoggerLevel(nhylog::LogLevel::value::WARN);
    builder->buildLoggerFormatter("[%c][%f:%l]%m%n");
    builder->buildSink<nhylog::FileSink>("./msg.log");
    builder->buildSink<nhylog::StdoutSink>();
    builder->buildSink<RollByTimeSink>("./RollByTime",GAP::GAP_SECOND);
    nhylog::Logger::ptr logger =  builder->build();

    logger->debug("%s","测试输出");
    logger->info("%s","测试输出");
    logger->warn("%s","测试输出");
    logger->error("%s","测试输出");
    logger->fatal("%s","测试输出");

}